<?php
/**
 * Created by PhpStorm.
 * User: ZD
 * Date: 2017/5/18 0018
 * Time: 上午 9:32
 */

namespace app\common;


use think\Controller;

class Benc extends Controller
{
	public function benc_resp($d)
	{
		$this->benc_resp_raw($this->benc(array('type' => 'dictionary', 'value' => $d)));
	}

	public function benc_resp_raw($x)
	{
		header("Content-Type: text/plain; Charset=utf-8");
		header("Pragma: no-cache");
		if ($_SERVER["HTTP_ACCEPT_ENCODING"] == "gzip") {
			header("Content-Encoding: gzip");
			echo gzencode($x, 9, FORCE_GZIP);
		} else {
			echo $x;
		}
	}

	public function err($msg)
	{
		$this->benc_resp(array('failure reason' => array('type' => 'string', 'value' => $msg)));
		exit();
	}

	public function benc($obj)
	{
		if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"])) {
			return;
		}
		$c = $obj["value"];
		switch ($obj["type"]) {
			case "string":
				return $this->benc_str($c);
			case "integer":
				return $this->benc_int($c);
			case "list":
				return $this->benc_list($c);
			case "dictionary":
				return $this->benc_dict($c);
			default:
				return;
		}
	}

	public function benc_str($s)
	{
		return strlen($s) . ":$s";
	}

	public function benc_int($i)
	{
		return "i" . $i . "e";
	}

	public function benc_list($a)
	{
		$s = "l";
		foreach ($a as $e) {
			$s .= $this->benc($e);
		}
		$s .= "e";

		return $s;
	}

	public function benc_dict($d)
	{
		$s = "d";
		$keys = array_keys($d);
		sort($keys);
		foreach ($keys as $k) {
			$v = $d[ $k ];
			$s .= $this->benc_str($k);
			$s .= $this->benc($v);
		}
		$s .= "e";

		return $s;
	}
}